package com.homework.ch10;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/14
 * @Description:
 */
public class Test10 {
    public static void main(String[] args) {
        final Object lock1 = new Object();
        final Object lock2 = new Object();
        Thread t1 = new Thread(() -> {
            synchronized (lock1) {
                System.out.println("线程1获取到了锁1");
                try {
                    Thread.sleep(1000); // 线程1睡眠1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程1试图获取锁2");
                synchronized (lock2) {
                    System.out.println("线程1获取到了锁2");
                }
            }
            System.out.println("线程1结束");
        });
        Thread t2 = new Thread(() -> {
            synchronized (lock2) {
                System.out.println("线程2获取到了锁2");
                try {
                    Thread.sleep(1000); // 线程2睡眠1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程2试图获取锁1");
                synchronized (lock1) {
                    System.out.println("线程2获取到了锁1");
                }
            }
            System.out.println("线程2结束");
        });
        // 启动线程
        t1.start();
        t2.start();
        // 等待线程完成
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程结束");
    }
}
